#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_008.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_008.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test8.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>    // 添加对string.h的包含以支持对strlen等函数的使用
#include <nettle/hmac.h>

#define THREADS_COUNT 5
#define ITERATIONS_COUNT 1000

// 线程参数结构
typedef struct {
    int thread_id;  // 线程编号
} thread_data_t;

// HMAC加密函数
void *hmac_encrypt_thread(void *args) {
    thread_data_t *data = (thread_data_t *)args;
    struct hmac_sha256_ctx hmac_ctx;
    unsigned char key[] = "this is a test key";
    unsigned char message[] = "this is a test message";
    unsigned char digest[SHA256_DIGEST_SIZE];

    // 初始化HMAC上下文
    hmac_sha256_set_key(&hmac_ctx, strlen((char *)key), key);
    
    printf("线程 #%d 开始加密操作...\\n", data->thread_id);
    
    // 在当前线程中执行多次HMAC操作
    for (int i = 0; i < ITERATIONS_COUNT; ++i) {
        hmac_sha256_update(&hmac_ctx, strlen((char *)message), message);
        hmac_sha256_digest(&hmac_ctx, SHA256_DIGEST_SIZE, digest);
    }

    printf("线程 #%d 完成加密操作。\\n", data->thread_id);

    pthread_exit(NULL);
}

int main() {
    pthread_t threads[THREADS_COUNT];
    thread_data_t thread_data[THREADS_COUNT];
    int ret;

    // 创建线程
    for (int i = 0; i < THREADS_COUNT; ++i) {
        thread_data[i].thread_id = i;
        ret = pthread_create(&threads[i], NULL, hmac_encrypt_thread, (void *)&thread_data[i]);
        if (ret) {
            fprintf(stderr, "创建线程 #%d 失败，返回代码：%d\\n", i, ret);
            exit(EXIT_FAILURE);
        }
    }

    // 等待所有线程完成
    for (int i = 0; i < THREADS_COUNT; ++i) {
        pthread_join(threads[i], NULL);
    }

    printf("所有线程执行完成。\\n");
    return 0;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test8 nettle_test8.c -lnettle -pthread')
        code, nettle_result = self.cmd("./nettle_test8")
        self.assertIn('所有线程执行完成', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test8 nettle_test8.c')
